<?php
/**
 * Created by PhpStorm.
 * User: wangsong
 * Time: 2018/5/29 15:52
 */

namespace App\Project\Sms;

use GuzzleHttp\Client;
use Illuminate\Support\Str;

class Ucpaas
{
    protected $url = 'https://open.ucpaas.com/ol/sms/sendsms';

    protected $body;

    public function __construct()
    {
        $this->body        = config('sms.connections.ucpaas');
        $this->body['uid'] = Str::random();
    }

    public function send($notifiable, UcpaasSmsInterface $sms)
    {
        $this->body['templateid'] = $sms->template();
        $this->body['param']      = $sms->parameters($notifiable);
        $this->body['mobile']     = $notifiable->phone;

        $client = new Client(['timeout' => 3]);

        try {
            $response = $client->post($this->url, [
                'headers' => [
                    'Accept'       => 'application/json',
                    'Content-Type' => 'application/json;charset=utf-8',
                ],
                'body'    => json_encode($this->body, 256)
            ]);
            $result   = json_decode($response->getBody()->getContents(), true);

            $sms->result($result['code'] == '000000');
        } catch (\Exception $exception) {
            \Log::warning($exception->getMessage(), $this->body);
        }
    }
}